import {createStore} from 'vuex'
import {getAllUsers,getAllGroups} from "../api/user";
import {findPerson} from "../utils/find"

const store = createStore({
    state: {
        //当前用户
        userId:'-1',
        user: {
            id: '-1',
            name: 'undefined',
            avatar: 'src/assets/img/pig.jpg',
            location: 'A区',
            note: '欢迎咨询'
        },
        // 会话列表
        sessions: [],
        // 当前选中的会话,初始为-1
        sessionId: '-1',
        session: {},

        //群聊列表
        groups: [],
        //当前群聊,初始为-1
        groupId: -1,
        group:{},

        //所有用户
        usersList: [
            {label: "常用联系人", id: '-1', children: [], avatar: null},
            {label: "护士站", id: '-1', children: [], avatar: null},
            {label: "科室", id: '-1', children: [], avatar: null}
        ],
        //当前选中的用户id，初始为-1
        personId: '-1',
        person: {},
        //常用联系人集合，存到localStorage
        contactsSet: [],
        //常用联系人列表
        contacts: [],
        //当前选中的用户是否是常用联系人
        isLike: false,

        // 过滤出只包含这个key的会话
        filterKey: '',
        //rightPage显示什么,0:空白页 1:私聊 2:详情 3:群聊
        rightPage:0,
    },
    mutations: {
        SET_MYINFO(state, data) {
            state.user = data
        },
        //初始化
        INIT_DATA(state) {
            //从localstorage初始化session
            if (!localStorage.getItem('session')) {
                state.sessions = []
            } else {
                state.sessions = JSON.parse(localStorage.getItem('session'));
            }
            //初始化当前session
            state.session = state.sessions.find(session => session.id == state.sessionId);

            //从api初始化群聊信息
            state.groups=getAllGroups();

            //从localstorage初始化contactsset
            if (!localStorage.getItem('contacts')) {
                state.contactsSet = ['1', '11', '21']
            } else {
                let jsonObj = JSON.parse(localStorage.getItem('contacts'));
                for (let i in jsonObj) {
                    if(jsonObj[i]!='-1'){
                        state.contactsSet.push(jsonObj[i]);}
                }
            }
            //更新contacts和列表数据
            let tSet = new Set(state.contactsSet);

            //从sessionStorage获取用户id
            state.userId= sessionStorage.getItem("ms_psd").toString()

            //从users：根据id获取用户信息、根据contactsset初始化常用联系人列表
            let users = getAllUsers();
            for (let i = 0; i < users.station.length; i++) {
                let t = users.station[i];
                if(t.id==state.userId){
                    state.user=t;
                }
                //如果联系人集合中包含该用户的id
                if (tSet.has(t.id)) {
                    state.contacts.push({
                        label: t.name,
                        id: t.id,
                        avatar: t.avatar,
                    });
                }
            }
            for (let i = 0; i < users.office.length; i++) {
                for (let j = 0; j < users.office[i].doctors.length; j++) {
                    let t = users.office[i].doctors[j];
                    if(t.id==state.userId){
                        state.user=t;
                    }
                    if (tSet.has(t.id)) {
                        state.contacts.push({
                            label: t.name,
                            id: t.id,
                            avatar: t.avatar,
                        });
                    }
                }
            }
            state.usersList[0].children = state.contacts

        },
        //更新医院列表信息，从api获取
        UPDATE_HOSPITAL(state) {
            let users = getAllUsers();
            //常用联系人列表
            state.usersList[0].children = state.contacts

            //护士站
            for (let i = 0; i < users.station.length; i++) {
                const newStation = {
                    label: users.station[i].name,
                    id: users.station[i].id,
                    avatar: users.station[i].avatar
                }
                if(newStation.id!=state.userId) {
                    state.usersList[1].children.push(newStation);
                }
            }
            //科室
            for (let i = 0; i < users.office.length; i++) {
                const newOffice = {
                    label: users.office[i].name,
                    id: '-1',
                    avatar: null,
                    children: []
                };
                for (let j = 0; j < users.office[i].doctors.length; j++) {
                    const newDoctor = {
                        label: users.office[i].doctors[j].name,
                        id: users.office[i].doctors[j].id,
                        avatar: users.office[i].doctors[j].avatar,
                    }
                    if(newDoctor.id!=state.userId) {
                        newOffice.children.push(newDoctor);
                    }
                }
                state.usersList[2].children.push(newOffice);
            }
        },
        //发送消息
        SEND_MESSAGE(state, data) {
            let session = state.sessions.find(item => item.id === state.sessionId);
            session.messages.push({
                content: data.str,
                date: new Date(),
                type: data.type,
                self: true,
            });
        },
        //接收消息
        RECEIVE_MESSAGE(state, data) {
            let newMessage={
                content: data.content,
                date: new Date(),
                type: data.type,
                self: false
            }
            let session = state.sessions.find(session=> session.id === data.from);
            if(typeof (session)!='undefined') {
                session.messages.push(newMessage);
                if(state.sessionId==data.from && state.rightPage==1){
                    session.lastCheck=newMessage.date;
                }
                session.redFlag= newMessage.date>session.lastCheck
                console.log("是否未读：",session.redFlag);
            }
            else{//发消息的人不在会话列表
                let current = findPerson(data.from)
                state.sessions.push({
                    id: data.from,
                    user: {
                        name: current.name,
                        img: current.avatar,
                    },
                    lastCheck:new Date(),
                    redFlag:true,
                    messages: [newMessage]
                });
            }
        },
        //选择会话
        SELECT_SESSION(state, id) {
            state.sessionId = id;
            state.session = state.sessions.find(session => session.id == id);
            state.session.lastCheck=new Date()
            state.session.redFlag=false;
            state.rightPage=1;
        },
        //添加会话
        ADD_SESSION(state, id) {
            state.showDetail = false;
            state.sessions.push({
                id: id,
                user: {
                    name: state.person.name,
                    img: state.person.avatar,
                },
                lastCheck:new Date(),
                redFlag:false,
                messages: []
            });
        },
        //删除会话
        DELETE_SESSION(state,id){
            let i=state.sessions.findIndex(session => session.id == id)
            state.sessions.splice(i, 1)
        },
        //选择列表
        SELECT_PERSON(state, id) {
            state.personId = id;
            let find = state.contactsSet.find(contact => contact == id);
            if (typeof (find) == "undefined") {
                state.isLike = false;
            } else {
                state.isLike = true;
            }
            //根据id找到currentperson对象
            if (id != '-1') {
                state.person = findPerson(id);
            }
            state.rightPage=2;
        },
        //添加收藏
        ADD_CONTACTS(state) {
            state.contactsSet.push(state.personId);
            // localStorage.setItem('contacts', JSON.stringify(state.contactsSet));
            let users = getAllUsers();
            for (let i = 0; i < users.station.length; i++) {
                let t = users.station[i];
                if (state.personId == t.id) {
                    state.contacts.push({
                        label: t.name,
                        id: t.id,
                        avatar: t.avatar,
                    });
                }
            }
            for (let i = 0; i < users.office.length; i++) {
                for (let j = 0; j < users.office[i].doctors.length; j++) {
                    let t = users.office[i].doctors[j];
                    if (state.personId == t.id) {
                        state.contacts.push({
                            label: t.name,
                            id: t.id,
                            avatar: t.avatar,
                        });
                    }
                }
            }
            state.usersList[0].children = state.contacts
        },
        //删除收藏
        REMOVE_CONTACTS(state) {
            // for (let i = 0; i < state.contactsSet.length; i++) {
            //     if (state.contactsSet[i] == state.personId) {
            //         state.contactsSet.splice(i, 1)
            //     }
            // }
            let i=state.contactsSet.findIndex(contact => contact == state.personId)
            state.contactsSet.splice(i, 1)
            // for (let i = 0; i < state.contacts.length; i++) {
            //     if (state.contacts[i].id == state.personId) {
            //         state.contacts.splice(i, 1)
            //     }
            // }
            let j=state.contacts.findIndex(contact => contact.id == state.personId)
            state.contacts.splice(j, 1)
            console.log("REMOVE_CONTACTS", state.contactsSet)
            state.usersList[0].children = state.contacts
        },
        //选择群聊
        SELECT_GROUP(state,id){
            state.groupId=id;
            state.group = state.groups.find(group => group.id == id);
            state.rightPage=3;
        },
        //添加群聊
        ADD_GROUP(state,newGroup){
            state.groups.push(newGroup);
        },
        // 搜索
        SET_FILTER_KEY(state, value) {
            state.filterKey = value;
        }
    },
    actions: {
        // initData: ({dispatch}) => dispatch('INIT_DATA'),
        // initHospital: ({dispatch}) => dispatch('INIT_HOSPITAL'),
        // sendMessage: ({dispatch}, content) => dispatch('SEND_MESSAGE', content),
        // selectSession: ({dispatch}, id) => dispatch('SELECT_SESSION', id),
        // selectPerson: ({dispatch}, id) => dispatch('SELECT_PERSON', id),
        // search: ({dispatch}, value) => dispatch('SET_FILTER_KEY', value),
        // setMyInfo: ({dispatch}, value) => dispatch('SET_MYINFO', value)
    },
    modules: {}
});

store.watch(
    (state) => state.contactsSet,
    (val) => {
        localStorage.setItem('contacts', JSON.stringify(val));
    },
    {deep: true}
);

store.watch(
    (state) => state.sessions,
    (val) => {
        localStorage.setItem('session', JSON.stringify(val));
    },
    {deep: true}
);

export default store;